package com.rest.demo.concurrent;

import java.util.Random;
import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * @author Administrator
 * @decription
 * @Date 2018-02-01 14:05
 */
public class CompletionServiceDemo {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        CompletionService<Integer> results = new ExecutorCompletionService<Integer>(executor);
        IntStream.range(0,5).forEach(i -> results.submit(() -> {
            int result = i;
            Thread.sleep(new Random().nextInt(5000));
            return result;
        }));
        IntStream.range(0,5).forEach(i -> {
            try {
                System.out.println(results.take().get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }
}
